﻿/*!
 * Copyright (c), 上海沃恩信息科技有限公司.
 * All rights reserved.
 * Licensed under BSD (https://www.pittypat.work/bsd.html).
 */

using System;
using System.Collections.Generic;
using System.IO;

namespace Pittypat
{
    /// <summary>
    /// 从通知服务查询到的通知列表。
    /// </summary>
    public sealed class NotificationList : IComplex
    {
        /// <summary>
        /// 表示一个空的通知消息列表。这是一个只读字段。
        /// </summary>
        public static readonly NotificationList Empty = new NotificationList(0, null);

        // 通知总数，包括紧急、特急和新通知
        private @int64 total;
        // 通知列表
        private IList<INotification> notifications;

        static readonly IList<INotification> EmptyNotifications = new INotification[0];

        /// <summary>
        /// 使用通知总数和通知列表初始化 <see cref="NotificationList"/> 的新实例。
        /// </summary>
        /// <param name="total">通知总数。</param>
        /// <param name="notifications">通知列表。</param>
        public NotificationList(@int64 total, IList<INotification> notifications)
        {
            this.total = total < 0 ? 0 : total;
            this.notifications = notifications ?? EmptyNotifications;
        }

        /// <summary>
        /// 获取通知总数，包括紧急、特急和新通知。
        /// </summary>
        public @int64 Total
        {
            get
            {
                return this.total;
            }
        }

        /// <summary>
        /// 获取当前查询到的通知列表。
        /// </summary>
        public IList<INotification> Notifications
        {
            get
            {
                return this.notifications;
            }
        }

        /// <summary>
        /// 将当前对象作为 JSON 字符串写入指定的文本流。
        /// </summary>
        /// <param name="writer">目标文本流。</param>
        /// <exception cref="ArgumentNullException">writer 为 null。</exception>
        public void Write(TextWriter writer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            writer.Write("{{\"total\":{0},\"notifications\":[", this.total);

            if (this.notifications != null && this.notifications.Count > 0)
            {
                var list = new List<INotification>(this.notifications.Count);

                // 排除 null 元素
                foreach (var item in this.notifications)
                {
                    if (item != null)
                    {
                        list.Add(item);
                    }
                }

                for (int i = 0; i < list.Count; ++i)
                {
                    list[i].Write(writer);

                    if (i < list.Count - 1)
                    {
                        writer.Write(',');
                    }
                }
            }

            writer.Write("]}");
        }
    }
}
